package com.cskaoyan.market.controller.admin;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.admin.MarketStorageService;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @MethodName AdminStorageController
 * @Description  图片上传
 * @Author M
 * @Date 16:04 2023/5/9
 **/

@RestController
@RequestMapping("admin/storage")
public class AdminStorageController {

    @Autowired
    private MarketStorageService storageService;

    /*
    {
    	"errno": 0,
    	"data": {
    		"id": 769,
    		"key": "o41mrioibvf2qm92yu1l.jpg",
    		"name": "1.jpg",
    		"type": "image/jpeg",
    		"size": 158043,
    		"url": "http://101.43.69.31:8083/wx/storage/fetch/o41mrioibvf2qm92yu1l.jpg",
    		"addTime": "2023-05-09 15:57:34",
    		"updateTime": "2023-05-09 15:57:34"
    	},
    	"errmsg": "成功"
    }
     */
    @PostMapping("create")
    public Object create(MultipartFile file) {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 获取后缀名
        int index = fileName.indexOf(".");
        String suffix = fileName.substring(index);
        //获取文件的mime类型

        String contentType = file.getContentType();
        // 大小
        int size = (int) file.getSize();
        // 新文件名 ：随机文件名+后缀
        String key = UUID.randomUUID().toString() + suffix;
        // 使用配置文件存储路径等信息
        // 获取信息
        // TODO；可以使用配置文件处理
        String upload = "F:/Java_code/JavaEE_Project/Project/image/";
        String domain = "http://localhost:8083";
        // 拼接文件的绝对路径
        String absolutePath = upload + key;
        // 上传
        try {
            file.transferTo(new File(absolutePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 写入数据库
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(fileName);
        marketStorage.setType(contentType);
        marketStorage.setSize(size);
        marketStorage.setUrl("/wx/storage/fetch/" + key);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorage.setDeleted(false);
        // 执行操作
        int row = storageService.addStorage(marketStorage);

        if (row != 1){
            // 添加失败
            return ResponseUtil.badArgument();
        }
        //对url进行一个更新，拼接出前面的主机、端口号部分
        marketStorage.setUrl(domain + marketStorage.getUrl());
        return ResponseUtil.ok(marketStorage);
    }
}
